<?php

namespace app\api\service;

use think\facade\Cache;

class Token
{
    public function getToken($val)
    {
        $token = $this->saveToCache($val);
        return $token;
    }
    public function getTokenVal($token)
    {
        $val = cache($token);
        $val = json_decode($val, true);
        return $val;
    }
    private function saveToCache($val)
    {
        $token = $this->generateToken();
        $data = json_encode($val);
        $result = cache($token, $data, config('secure.expire_time'));
        if (!$result) {
            return error('服务器缓存异常');
        }
        return $token;
    }
    // 自动续长token时间
    public function autoExpireTime($token)
    {
        $val = cache($token);
        $data = json_decode($val, true);
        $et = config('secure.expire_time');
        $data['expire_time'] = time() + $et;
        $saveData = json_encode($data);
        cache($token, $saveData, $et);
    }
    public function generateToken()
    {
        $time = request()->time(true);
        $token = md5(randStr(18) . config('secure.secure_salt') . $time);
        return $token;
    }
}
